#!/usr/bin/env python3
"""
DeepSeek API 网络连接诊断工具
用于诊断API连接问题
"""

import requests
import socket
import subprocess
import sys
import os
import time

def test_dns_resolution(hostname):
    """测试DNS解析"""
    try:
        print(f"测试DNS解析: {hostname}")
        ip_address = socket.gethostbyname(hostname)
        print(f"✓ DNS解析成功: {hostname} -> {ip_address}")
        return True
    except socket.gaierror:
        print(f"✗ DNS解析失败: 无法解析 {hostname}")
        return False

def test_port_connectivity(hostname, port):
    """测试端口连接性"""
    try:
        print(f"测试端口连接: {hostname}:{port}")
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(5)
        result = sock.connect_ex((hostname, port))
        sock.close()
        
        if result == 0:
            print(f"✓ 端口 {port} 连接成功")
            return True
        else:
            print(f"✗ 端口 {port} 连接失败 (错误代码: {result})")
            return False
    except Exception as e:
        print(f"✗ 端口连接测试异常: {e}")
        return False

def test_http_request(url, api_key=None):
    """测试HTTP请求"""
    try:
        print(f"测试HTTP请求: {url}")
        headers = {}
        if api_key:
            headers["Authorization"] = f"Bearer {api_key}"
        
        response = requests.get(url, headers=headers, timeout=10)
        print(f"✓ HTTP请求成功: 状态码 {response.status_code}")
        return True
    except requests.exceptions.Timeout:
        print("✗ HTTP请求超时")
        return False
    except requests.exceptions.ConnectionError:
        print("✗ HTTP连接错误")
        return False
    except Exception as e:
        print(f"✗ HTTP请求异常: {e}")
        return False

def test_api_endpoint(api_url, api_key):
    """测试API端点"""
    try:
        print(f"测试API端点: {api_url}")
        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
        
        # 发送一个简单的测试请求
        payload = {
            "model": "deepseek-chat",
            "messages": [{"role": "user", "content": "test"}],
            "max_tokens": 5
        }
        
        start_time = time.time()
        response = requests.post(api_url, headers=headers, json=payload, timeout=15)
        end_time = time.time()
        
        if response.status_code == 200:
            print(f"✓ API请求成功: 状态码 {response.status_code}, 响应时间: {end_time - start_time:.2f}秒")
            return True
        elif response.status_code == 401:
            print("✗ API密钥无效: 401 Unauthorized")
            return False
        else:
            print(f"✗ API请求失败: 状态码 {response.status_code}")
            print(f"响应内容: {response.text}")
            return False
            
    except requests.exceptions.Timeout:
        print("✗ API请求超时 (15秒)")
        return False
    except Exception as e:
        print(f"✗ API请求异常: {e}")
        return False

def main():
    print("=" * 60)
    print("DeepSeek API 网络连接诊断工具")
    print("=" * 60)
    
    api_key = "sk-b1280f0b9f6844629c9951d5da297473"
    api_host = "api.deepseek.com"
    api_port = 443
    api_url = "https://api.deepseek.com/v1/chat/completions"
    
    print(f"API密钥: {api_key[:10]}...{api_key[-4:]}")
    print(f"API主机: {api_host}")
    print(f"API端口: {api_port}")
    print()
    
    # 执行诊断测试
    tests_passed = 0
    total_tests = 4
    
    # 测试1: DNS解析
    if test_dns_resolution(api_host):
        tests_passed += 1
    print()
    
    # 测试2: 端口连接
    if test_port_connectivity(api_host, api_port):
        tests_passed += 1
    print()
    
    # 测试3: HTTP连接
    if test_http_request(f"https://{api_host}"):
        tests_passed += 1
    print()
    
    # 测试4: API端点测试
    if test_api_endpoint(api_url, api_key):
        tests_passed += 1
    print()
    
    # 总结结果
    print("=" * 60)
    print("诊断结果汇总:")
    print(f"通过测试: {tests_passed}/{total_tests}")
    
    if tests_passed == total_tests:
        print("✓ 所有测试通过，网络连接正常")
    else:
        print("✗ 存在网络连接问题")
        print("\n建议解决方案:")
        print("1. 检查网络连接是否正常")
        print("2. 尝试使用其他网络（如手机热点）")
        print("3. 检查防火墙设置")
        print("4. 验证API密钥是否有效")
        print("5. 等待一段时间后重试（可能是服务器问题）")

if __name__ == "__main__":
    main()
